from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.views.decorators.http import require_POST, require_http_methods
from .models import TodoItem
from django.contrib.auth.models import User


@login_required
def todo_list(request):
    todos = TodoItem.objects.filter(owner=request.user).order_by('created_at')
    return render(request, 'todo/todo_list.html', {'todos': todos})

@login_required
@require_POST
def add_todo(request):
    task_text = request.POST.get('task_text')
    if task_text:
        todo = TodoItem.objects.create(task_text=task_text, owner=request.user)
        return render(request, 'todo/partials/todo_item.html', {'todo': todo})
    return HttpResponse(status=204)

@login_required
@require_POST
def toggle_todo(request, todo_id):
    todo = get_object_or_404(TodoItem, id=todo_id, owner=request.user)
    todo.completed = not todo.completed
    todo.save()
    return render(request, 'todo/partials/todo_item.html', {'todo': todo})

@login_required
@require_http_methods(["DELETE"])
def delete_todo(request, todo_id):
    todo = get_object_or_404(TodoItem, id=todo_id, owner=request.user)
    todo.delete()
    return HttpResponse(status=200)

@login_required
def admin_view(request):
    if not request.user.is_staff:
        return HttpResponse("Unauthorized", status=401)
    
    all_todos = TodoItem.objects.all().order_by('owner', 'created_at')
    return render(request, 'todo/admin_view.html', {'all_todos': all_todos})